package cn.jtool.dig.server.comm;

import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.SessionManager;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class MessageExchange {

    public static void upData(Packet packet){
        Session tunnelSession = SessionManager.getSession(packet.getHeader().getDigId());
        if(Objects.nonNull(tunnelSession)){
            VirtualChannel virtualChannel = VirtualChannelManager.getVirtualChannelByVirtualChannelId(packet.getHeader().getChannelId());
            if(Objects.nonNull(virtualChannel)){
                tunnelSession.getChannelHandlerContext().writeAndFlush(packet);
            }else{
                log.error("[虚拟]连接未建立, 数据放入暂存区");
                StageManager.addStage(packet.getHeader().getChannelId(), packet);
            }
        }else{
            log.error("[tunnel]连接未建立, 关闭当前连接");
            Session realSession = SessionManager.getSession(packet.getHeader().getChannelId());
            if(Objects.nonNull(realSession)){
                realSession.disconnect();
            }
        }
    }

    public static void upAdmin(Packet packet){
        Session tunnelSession = SessionManager.getSession(packet.getHeader().getDigId());
        if(Objects.isNull(tunnelSession)){
            log.error("[tunnel]连接未建立, 关闭当前连接");
            Session realSession = SessionManager.getSession(packet.getHeader().getChannelId());
            if(Objects.nonNull(realSession)){
                realSession.disconnect();
            }
        }else{
            tunnelSession.getChannelHandlerContext().writeAndFlush(packet);
        }
    }
}
